<template>
  <div class="shopping-cart">
    <h1 v-if="success">{{ msg }}</h1>
    <div v-else>
      <table>
        <caption>
          <h3>商品结算</h3>
        </caption>
        <tr>
          <th></th>
          <th>商品名称</th>
          <th>单价</th>
          <th>数量</th>
          <th>金额</th>
        </tr>
        <tr v-for="book in books" :key="book.id">
          <td><img :src="book.imgUrl" alt="" /></td>
          <td>
            <router-link
              :to="{ name: 'book', params: { id: book.id } }"
              target="_blank"
            >
              {{ book.title }}
            </router-link>
          </td>
          <td>{{ currency(book.price) }}</td>
          <td>
            {{ book.quantity }}
          </td>
          <td>{{ currency(cartItemPrice(book.id)) }}</td>
        </tr>
      </table>
      <p>
        <span><button class="pay" @click="pay">付款</button></span>
        <span>总价：{{ currency(cartTotalPrice) }}</span>
      </p>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapState, mapMutations } from "vuex";
export default {
  name: "Checkout",
  data() {
    return {
      success: false,
      msg: "付款成功！",
    };
  },
  inject: ["currency"],
  computed: {
    ...mapState("cart", {
      books: "items",
    }),
    ...mapGetters("cart", ["cartItemPrice", "cartTotalPrice"]),
  },
  methods: {
    itemPrice(price, count) {
      return price * count;
    },
    ...mapMutations("cart", ["setCartItems"]),
    pay() {
      this.setCartItems({ items: [] });
      this.success = true;
    },
  },
};
</script>
<style scoped>
.shopping-cart {
  width: 900px;
  margin: 50px auto;
  padding-bottom: 50px;
}
table {
  border: 1px solid #ccc;
  width: 100%;
  border-radius: 10px;
  box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.301);
  padding: 0 20px;
}
p {
  margin-top: 50px;
}
th {
  height: 50px;
}
th,
td {
  text-align: center;
  padding: 30px 0;
  border-bottom: 1px solid #ccc;
}
td {
  flex: 1;
}
span {
  padding: 0 10px;
  line-height: 30px;
  float: right;
}
button {
  cursor: pointer;
  border: 1px solid#3a8efd;
  border-radius: 10px;
  width: 50px;
  height: 30px;
  color: #3a8efd;
  background: white;
  transition: 0.2s;
}
button:hover {
  color: white;
  background: #3a8efd;
}
h1,
h3 {
  text-align: center;
}
</style>
